<template>
  <div class="studentInfo">
    <el-form :label-position="'right'" label-width="92px" :model="studentInfo" :rules="rules" ref="form"
      class="myInfomation">
      <el-form-item label="学校：" prop="schoolWorkplaceID">
        <el-select v-model="studentInfo.schoolWorkplaceID" placeholder="请输选择在读学校">
          <el-option v-for="item in school" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="姓名：" prop="realName">
        <el-input
          v-model="studentInfo.realName"
          placeholder="请输入真实姓名"
          @keypress.enter.native.prevent
        ></el-input>
      </el-form-item> -->
      <el-form-item label="学院：" prop="departmentID">
        <el-select v-model="studentInfo.departmentID" filterable placeholder="请选择学院">
          <el-option v-for="item in deptList" :key="item.departmentID" :label="item.name" :value="item.departmentID">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="专业：" prop="majorID">
        <el-select v-model="studentInfo.majorID" filterable placeholder="请选择专业">
          <el-option v-for="item in filterMajorList" :key="item.majorID" :label="item.name" :value="item.majorID" :disabled="item.disabled">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班级：" prop="classID">
        <el-select v-model="studentInfo.classID" size="small" filterable placeholder="请选择所在班级" key="selectClass">
          <el-option v-for="item in filterClassList" :key="item.classID" :label="item.className" :value="item.classID" :disabled="item.disabled">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="非常规班：" prop="otherClassIDList">
        <el-select v-model="studentInfo.otherClassIDList" multiple size="small" filterable placeholder="请选择非常规班级" key="selectClass">
          <el-option v-for="item in filterOtherClassList" :key="item.classID" :label="item.className" :value="item.classID" :disabled="item.disabled">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学号：" prop="stuNum">
        <el-input v-model="studentInfo.stuNum" placeholder="请输入学号" @keypress.enter.native.prevent></el-input>
      </el-form-item>
      <el-form-item label="入学年份：" prop="enrollYear">
        <el-select v-model="studentInfo.enrollYear" placeholder="请选择入学年份">
          <el-option v-for="item in years" :key="item" :label="item" :value="item">
          </el-option>
        </el-select>
      </el-form-item>

      <div class="btnBox">
        <button @click.prevent="handelConfirm">保存</button>
      </div>
      <!-- <button @click.prevent="test" v-if="userInfo.userID === 228">创建1</button> -->
      <!-- <button @click.prevent="test2" v-if="userInfo.userID === 228">创建2</button> -->
    </el-form>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { updateUserInfo } from "@/request/user";
import { getClassList, getMajorList, getDeptList, createDept, createMajor, createClass } from "@/request/user";
export default {
  data() {
    return {
      studentInfo: {
        schoolWorkplaceID: "",
        realName: "",
        stuNum: null,
        className: "",
        classID: null, // 班级ID
        otherClassIDList: [],
        majorID: "", // 专业ID
        departmentID: "", // 学院ID
        enrollYear: "", // 入学年份
      },
      rules: {
        schoolWorkplaceID: [
          {
            required: true,
            message: "请输入学校名称",
            trigger: "blur",
          },
        ],
        realName: [
          {
            required: true,
            message: "请输入真实姓名",
            trigger: "blur",
          },
        ],
        stuNum: [
          {
            required: true,
            message: "请输入学号",
            trigger: "blur",
          },
          // {
          //   type: "number",
          //   message: "请输入正确的学号",
          //   trigger: "blur",
          // },
        ],
        classID: [
          {
            required: true,
            message: "请输入班级名称",
            trigger: "blur",
          },
        ],
        majorID: [
          {
            required: true,
            message: "请选择专业",
            trigger: "blur",
          },
        ],
        departmentID: [
          {
            required: true,
            message: "请选择学院",
            trigger: "blur",
          },
        ],
        enrollYear: [
          {
            required: true,
            message: "请选择入学年份",
            trigger: "blur",
          },
        ],
      },
      school: [
        {
          id: 1,
          name: "顺德职业技术学院",
        },
      ],
      majors: [
        {
          id: 1,
          name: "软件技术",
        },
      ], // 专业列表
      faculty: [
        {
          id: 1,
          name: "智能制造学院",
        },
      ], // 学院列表
      years: [], // 入学年份
      deptList: [], // 学院列表
      majorList: [], // 专业列表
      classList: [], // 班级列表
      isFirstChangeM: true,
      isFirstChangeJ: true,
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    filterClassList() {
      if (this.studentInfo.majorID) {
        return this.classList.filter(item => item.majorID == this.studentInfo.majorID && item.classType == '常规班')
      } else return [{
        majorID: 0,
        classID: 0,
        otherClassIDList: [],
        className: "请选择专业",
        disabled: true
      }]
    },
    filterOtherClassList() {
      return this.classList.filter(item => item.classType == '非常规班' || !item.classType)
    },
    filterMajorList() {
      if (this.studentInfo.departmentID) {
        return this.majorList.filter(item => item.departmentID == this.studentInfo.departmentID)
      } else return [{
        majorID: '请选择学院',
        departmentID: 0,
        disabled: true
      }]
    },
  },
  created() {
    this.computedYear();
    this.gClassList();
    this.gDeptList();
    this.gMojorList();
    // 设置属性
    Object.keys(this.studentInfo).forEach((item) => {
      let otherClassIDList = this.userInfo['otherClassIDList']
      if (item == 'otherClassIDList' && otherClassIDList) {
        otherClassIDList = otherClassIDList?.split(',')?.map(i => parseInt(i))
        this.studentInfo[item] = otherClassIDList
      } else this.studentInfo[item] = this.userInfo[item];
    });
  },
  watch: {
    "studentInfo.classID"(n) {
      this.studentInfo.className = this.classList.find(
        (item) => item.classID == this.studentInfo.classID
      )?.className || '';
    },
    'studentInfo.majorID'(n) {
      if (this.isFirstChangeJ) return this.isFirstChangeJ = false
      if (this.studentInfo.classID) {
        const includes = this.filterClassList.every(item => item.classID == this.studentInfo.classID)?.length
        if (!includes) this.studentInfo.classID = null
      }
    },
    'studentInfo.departmentID'(n) {
      if (this.isFirstChangeM) return this.isFirstChangeM = false
      if (this.studentInfo.majorID) {
        const includes = this.filterMajorList.every(item => item.majorID == this.studentInfo.majorID)?.length
        if (!includes) this.studentInfo.majorID = null
      }
    }
  },
  methods: {
    /**
     * @description 检查表单
     * @param {'form'} 表单名称
     */
    handelConfirm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 信息校验成功
          this.handelSubmit();
        } else {
          // 信息校验不通过
          return false;
        }
      });
    },
    /**
     * @description 提交信息
     */
    handelSubmit() {
      const { realName } = this.studentInfo;

      let params = {
        userfromschool: Object.assign(
          { userID: this.userInfo.userID },
          this.studentInfo
        ),
        // userdetail: {
        //   realName,
        // },
      };
      if (params.userfromschool.otherClassIDList) {
        params.userfromschool.otherClassIDList = params.userfromschool.otherClassIDList.join(',')
      }
      updateUserInfo(params).then((res) => {
        if (res.errno === 0) {
          // 重新获取用户信息
          this.$store.dispatch("user/reacquireUserInfo", params.userfromschool);
          this.$antdMessage.success({
            content: "修改成功！",
          });
        } else {
          this.$antdMessage.error({
            content: res.message || "修改失败！",
          });
        }
      });
    },
    // 计算年份
    computedYear() {
      const earliestYear = 2017;
      const currYear = new Date().getFullYear();
      const currMonth = new Date().getMonth() + 1;
      this.years.push(earliestYear);
      // 到每年的9月份 才把今年加入 一般入学时间为9月
      for (
        let i = 0;
        i < (currYear) - 2017;
        i++
      ) {
        this.years.push(earliestYear + (i + 1));
      }
    },
    // 获取学院列表
    async gDeptList() {
      const data = await getDeptList();
      if (data) this.deptList = data
      else this.$antdMessage.error({ content: "获取学院列表失败" });
    },
    // 获取专业列表
    async gMojorList(params) {
      const data = await getMajorList(params);
      if (data) this.majorList = data
      else this.$antdMessage.error({ content: "获取专业列表失败" });
    },
    // 获取班级列表
    async gClassList() {
      const data = await getClassList({classType: 'all'});
      if (data) this.classList = data;
      else
        this.$antdMessage.error({ content: "获取班级列表失败" });
    },
    // test() {
    //   const params = {
    //     // deptName: "测试创建dept2"
    //     // majorName: "测试创建major", 
    //     // departmentID: 5,
    //     classType: "非常规班",
    //     className: "2023上学期网页设计技术公选", 
    //     majorID: 1
    //   }
    //   // createMajor
    //   // createClass
    //   //createDept
    //   createClass(params).then(res => {
    //     console.log(res);
    //   })
    //   console.log(params);
    // },
    // test2() {
    //   const params = {
    //     // deptName: "测试创建dept2"
    //     // majorName: "测试创建major", 
    //     // departmentID: 5,
    //     className: "2022网页公选周盛华班", 
    //     majorID: 1
    //   }
    //   // createMajor
    //   // createClass
    //   //createDept
    //   console.log(params);
    //   createClass(params).then(res => {
    //     console.log(res);
    //   })
    // }
  },
};
</script>

<style lang="stylus">
.studentInfo {
  .el-form-item {
    .el-form-item__label {
      height: 30px;
      line-height: 30px;
      font-family: Segoe UI;
      font-size: 16px;
      color: #909090;
    }

    .el-form-item__content {
      line-height: 30px;

      .el-input {
        .el-input__inner {
          border: solid 1px rgba(112, 112, 112, 0.6);
        }
      }

      .el-select {
        .el-input__suffix {
          right: 0;

          .el-input__suffix-inner {
            .el-input__icon {
              line-height: 30px;
              transform: rotate(360deg);
            }

            .is-reverse {
              transform: rotate(540deg);
            }

            .el-select__caret::before {
              content: '\e790';
            }
          }
        }
      }
    }
  }

  .btnBox {
    button {
      margin-left: 90px;
      cursor: pointer;
      outline: none;
      width: 50px;
      height: 25px;
      background-color: #f6061e;
      border-radius: 5px;
      // border: solid 1px #f6061e;
      borde: none;
      font-family: Segoe UI;
      font-size: 14px;
      color: #ffffff;
    }
  }
}
</style>